package com.rocketmq.demo.order;

import org.apache.rocketmq.client.exception.MQClientException;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.apache.rocketmq.client.producer.MessageQueueSelector;
import org.apache.rocketmq.client.producer.SendResult;
import org.apache.rocketmq.common.message.Message;
import org.apache.rocketmq.common.message.MessageQueue;

import java.util.ArrayList;
import java.util.List;

/**
 * @ProjectName: rocketmq-demo
 * @Package: com.rocketmq.demo.order
 * @ClassName: Producer
 * @Author: mac
 * @Description:
 * @Date: 2021/4/20 3:41 下午
 * @Version: 1.0
 */
public class Producer {

    public static void main(String[] args) {
        //1.创建消息生产者,并指定生产者组
        DefaultMQProducer producer = new DefaultMQProducer("group1");

        //2.指定nameservice地址
        producer.setNamesrvAddr("192.168.31.67:9876;192.168.31.126:9876;192.168.31.209:9876");

        try {
            //3.启动生产者producer
            producer.start();
            //构建集合消息
            List<OrderStep> orderSteps = OrderStep.buildOrders();

            for (int i = 0; i < orderSteps.size(); i++) {

                String body = orderSteps.get(i) + "";
                Message msg = new Message("OrderTopic", "Order", "i" + i, body.getBytes());

                //4.发送消息
                /**
                 * 参数一：消息对象
                 * 参数二：消息队列的选择器
                 * 参数三：选择队列的业务标识（订单ID）
                 */
                SendResult sendResult = producer.send(msg, new MessageQueueSelector() {
                    /**
                     *
                     * @param mqs：队列集合
                     * @param msg：消息对象
                     * @param arg：业务标识的参数
                     * @return
                     */
                    @Override
                    public MessageQueue select(List<MessageQueue> mqs, Message msg, Object arg) {
                        long orderId = (long) arg;
                        long index = orderId % mqs.size();
                        return mqs.get((int) index);
                    }
                }, orderSteps.get(i).getOrderId());
                //5.消息发送结果
                System.out.println("发送结果：" + sendResult);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            //6.关闭生产者
            producer.shutdown();
        }


    }
}
